package com.woniuxy.creditsystem.loanmag.controller;

import com.github.pagehelper.PageInfo;
import com.woniuxy.creditsystem.common.bean.LoanQuery;
import com.woniuxy.creditsystem.common.bean.LoansInfo;
import com.woniuxy.creditsystem.common.bean.ResultMsg;
import com.woniuxy.creditsystem.loanmag.service.LoanService;
import com.woniuxy.creditsystem.util.Analysis;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * author wangwang
 */
@RequestMapping("/poi")
@RestController
public class POIController {
    @Resource
    private LoanService loanService;
    //导出之:先将页面table解析为excel并保存到本地服务器磁盘
    @RequestMapping(value = "gettabledata",produces = {"application/json;charset=utf-8"})
    public ResultMsg getExcel(@RequestBody LoanQuery loanQuery) throws IOException {
        List<LoansInfo> list =null;
        if (loanQuery.getLimit()==0){
            //表示前台想要导出全部
            list = loanService.exportall(loanQuery);
            System.out.println(list.size());
        }else{
            //表示前台只想查询当前页,则借助pagehelper
            PageInfo<LoansInfo> pageInfo = loanService.findByQuery(loanQuery);
            list = pageInfo.getList();
            System.out.println(list.size());
        }
        //将查询到的表格信息开始往excel表填充;
        //设置表对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建时间戳作为表名
        Date date = new Date();
        long time = date.getTime();
        String tableName = time+"";
        //创建表页面
        HSSFSheet sheet = workbook.createSheet("tableinfo");
        //用Excel表对象创建CellStyle对象
        CellStyle cellStyle = workbook.createCellStyle();
        //用Excel表对象获取CreationHelper对象
        CreationHelper createHelper = workbook.getCreationHelper();
        //给cellStyle对象设置Date格式
        cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
        for (int i = 1; i <list.size()+1 ; i++) {   //空出一行的目的是留个位置让用户自己去填充字段名,不空也行
            //创建每一行
            HSSFRow rowy = sheet.createRow(i);
            //给每一行添加数据
            HSSFCell celly1 = rowy.createCell(0);
            celly1.setCellValue(i); //第一列就是序号的意思

            HSSFCell celly2 = rowy.createCell(1);
            celly2.setCellValue(list.get(i-1).getOrderid());     //订单编号

            HSSFCell celly3 = rowy.createCell(2);
            celly3.setCellValue(list.get(i-1).getProductName()); //产品名称

            HSSFCell celly4 = rowy.createCell(3);
            celly4.setCellValue(list.get(i-1).getClientName());  //客户名称

            HSSFCell celly5 = rowy.createCell(4);

            celly5.setCellValue(list.get(i-1).getMoney().toString()); //贷款资金

            HSSFCell celly6 = rowy.createCell(5);
            celly6.setCellValue(list.get(i-1).getStatus());   //订单状态

            HSSFCell celly7 = rowy.createCell(6);
            //设置时间格式
            celly7.setCellStyle(cellStyle);
            celly7.setCellValue(list.get(i-1).getOrderTime());//下单时间
        }
        //创建文件夹
        String dir="D://poi";
        File file = new File(dir);
        if (!file.exists()){
            file.mkdir();
        }
        FileOutputStream os = new FileOutputStream("D://poi/"+tableName+".xls");

        workbook.write(os);  //poi内置方法，将当前文件写进这个流，也就是说把这个文件保存到这个路径去，但目前文件仍然在服务器端;
        os.flush();
        os.close();
        //设置响应数据
        ResultMsg msg = new ResultMsg();
        msg.setCode(200);
        msg.setMsg("D://poi/"+tableName+".xls");//将保存excel表的位置告诉前台，让前台用a标签去找;因为ajax和axios都解析不了二进制流;
        return msg;
    }
    /**
     *
     * @param path  文件在服务器的路径，由a标签携带
     * @param userAgent  用来判断是否是ie浏览器的一个响应头
     * @return 设置响应头额实体对象
     */
    //导出之再根据文件名将文件以流的形式返回给a标签
    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(String path,@RequestHeader("User-Agent") String userAgent){
        System.out.println("文件路径为:"+path);
        //判断当前路径是否有文件
        File file = new File(path);
        if(!file.exists()){
            return null;
        }
        //构建状态码200
        ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
        //设置文件长度
        builder.contentLength(file.length());
        //告诉前端，相应数据位二进制流
        builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            String fileName = URLEncoder.encode("table.xls","UTF-8");
            if(userAgent.indexOf("MSIE")>0){
                builder.header("Content-Disposition","attachment;filename="+fileName);
            }else {
                builder.header("Content-Disposition","attacher;filename*=UTF-8''"+fileName);
            }
            //通过fileutil工具类将文件读取到相应实体中
            return builder.body(FileUtils.readFileToByteArray(file));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //文件响应回去后就将服务器的文件删除掉，避免内存的溢出
            file.delete();
            System.out.println("文件已删除");
        }
        return null;
    }

    //导入到服务器数据库
    @RequestMapping(value = "port",produces = {"application/json;charset=utf-8"})
    public ResultMsg export(@RequestParam("file")MultipartFile file) throws IOException {
        ArrayList<ArrayList> list = Analysis.analysis(file);
        System.out.println(list);
        //将数据存入数据库


        ResultMsg msg = new ResultMsg();
        msg.setCode(200);
        msg.setMsg("上传成功");
        return msg;
    }

}
